<template>
    <div>
        <!-- 卡片区域 -->
        <el-card class="box-card">
            <!--            <el-row :gutter="20">-->
            <!--                <el-col :span="7">-->
            <!--                    <el-input placeholder="请输入内容" size="small" class="input-with-select" clearable>-->
            <!--                        <el-button slot="append" icon="el-icon-search"></el-button>-->
            <!--                    </el-input>-->
            <!--                </el-col>-->
            <!--            </el-row>-->
            <el-row :gutter="20">
                <el-col :span="20">
                    <el-tooltip effect="dark" content="刷新" placement="top" :enterable="false">
                        <el-button type="primary" size="small" :icon="icon" @click="getCommunityList"></el-button>
                    </el-tooltip>
                    <el-button type="primary" size="small" v-has="'admin/save_community'" @click="addDialogVisible = true">添加社区</el-button>

                    <el-button type="success" size="small" v-has="'admin/download_file'" @click="templateDownload">数据模版</el-button>
                    <el-upload
                            class="upload-demo inline-block"
                            :action="upload.url"
                            :headers="upload.headers"
                            :name="upload.name"
                            :accept="upload.accept"
                            :before-upload="handleBeforeUpload"
                            :limit="1" :on-success="handleSuccess" :show-file-list="false">
                        <el-button type="warning" v-has="'admin/import_excel'" size="small">数据导入</el-button>
                    </el-upload>
                </el-col>
            </el-row>
            <el-table :data="communityData" border stripe v-loading="loading"
                      element-loading-text="拼命加载中"
                      element-loading-spinner="el-icon-loading">
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="name" label="名称"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.status"
                                :active-value="1"
                                :inactive-value="2"
                                active-color="#13ce66"
                                inactive-color="#ff4949" v-has="'admin/set_community_status'"  @change="statusChange(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-tooltip effect="dark" v-has="'admin/read_community'" content="编辑" placement="top" :enterable="false">
                            <el-button type="primary" icon="el-icon-edit" size="mini"
                                       @click="editDialog(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" v-has="'admin/community_delete'" content="删除" placement="top" :enterable="false">
                            <el-button type="danger" icon="el-icon-delete" size="mini"
                                       @click="delComm(scope.row.id)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.page"
                    :page-sizes="[10, 20, 30, 40,50]"
                    :page-size="queryInfo.limit"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户的对话框 -->
        <el-dialog :title="title" :visible.sync="addDialogVisible" ref="dialogComponent" width="50%"
                   @close="resetForm('addFormRef')">
            <!--内容主题区 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" class="demo-ruleForm">
                <el-form-item label="名称" prop="name">
                    <el-input size="small" v-model="addForm.name"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch
                            v-model="addForm.status"
                            active-value="1"
                            inactive-value="2"
                            active-color="#13ce66"
                            inactive-color="#ff4949">
                    </el-switch>
                </el-form-item>
            </el-form>
            <!--底部按钮区 -->
            <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="resetForm('addFormRef')">取 消</el-button>
        <el-button size="small" @click="saveCommunity('addFormRef')" type="primary">确 定</el-button>
      </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: "index",
    data() {
        return {
            communityData: [],
            icon: 'el-icon-refresh',
            loading: true,
            title: '添加社区',
            addDialogVisible: false,
            queryInfo: {
                limit: this.$global_limit,
                page: this.$global_page
            },
            total: 0,
            addForm: {
                name: '',
                status: "1"
            },
            addFormRules: {
                name: [
                    {required: true, message: '请输入社区名称', trigger: 'blur'},
                ],
            },
            //上传
            upload: {
                url: this.$action_url + 'admin/import_excel',
                accept: '.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                headers: {Authorization: window.sessionStorage.getItem('token')},
                name: 'file',
            },
        }
    },
    created() {
        this.getCommunityList()
    },
    methods: {
        //数据源
        async getCommunityList() {
            const {data: res} = await this.$http.get('admin/community_list', {params: this.queryInfo})
            if (res.code !== 200) return this.$message.error(res.data.message)
            this.communityData = res.data.list
            this.total = res.data.totalCount
            this.loading = false
            this.icon = 'el-icon-refresh'
        },
        handleSizeChange(newSize) {
            this.queryInfo.limit = newSize
            this.getCommunityList()
        },
        handleCurrentChange(newPage) {
            this.queryInfo.page = newPage
            this.getCommunityList()
        },
        saveCommunity(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (!valid) return this.$message.error('输入不合法')
                const {data: result} = await this.$http.post('admin/save_community', this.addForm)
                if (result.code !== 200) return this.$message.error(result.data.message)
                this.$message.success('添加成功')
                this.addDialogVisible = false
                await this.getCommunityList()
            })
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        //更改状态
        async statusChange(row) {
            const {data: res} = await this.$http.post('admin/set_community_status', {id: row.id, status: row.status})
            if (res.code !== 200) return this.$message.error('获取数据失败')
            row.status = row.status !== 1 ? 2 : 1
            return this.$message.success('处理成功')
        },
        async editDialog(id) {
            this.title = '编辑项目';
            this.addDialogVisible = true
            this.$nextTick(() => {
                this.$refs["dialogComponent"].showDialog = true;
            });
            //结构赋值
            const {data: res} = await this.$http.get('admin/read_community/' + id)
            if (res.code !== 200) return this.$message.error(res.data.message)

            this.addForm = res.data.list
        },
        //删除
        async delComm(id) {
            const configResult = await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err);
            if (configResult !== 'confirm') return this.$message.info('已取消删除')
            const {data: result} = await this.$http.get('admin/community_delete/' + id)
            if (result.code !== 200) return this.$message.error(result.data.message)
            this.$message.success('删除成功')

            //删除成功后页码改变返还为上一页
            let totalPage = Math.ceil((this.total - 1) / this.queryInfo.limit);
            let currentPage = this.queryInfo.page > totalPage ? totalPage : this.queryInfo.page;
            this.queryInfo.page = this.queryInfo.page < 1 ? 1 : currentPage;

            await this.getCommunityList();
        },
        handleBeforeUpload() {
            this.loading = true
        },
        handleSuccess(response) {
            if (response.code !== 200) return this.$message.error('上传失败')
            this.loading = false
            this.$message.success('上传成功')
            this.getCommunityList();
        },
        // 下载按钮
        async templateDownload () {
            const configResult = await this.$confirm('确定下载该数据模板吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (configResult !== 'confirm') return this.$message.info('已取消下载')
            this.isDisabled = true
            const { data: res } = await this.$http.get('admin/download_file', { responseType: 'blob' })
            this.downloadFile(res)
            this.isDisabled = false
        },
        // blob下载方法
        downloadFile (url) {
            const blob = new Blob([url], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
            const objecturl = window.URL.createObjectURL(blob)
            const creEleA = document.createElement('a')
            creEleA.setAttribute('href', objecturl)
            creEleA.setAttribute('download', '数据导入模板')
            creEleA.click()
        }
    }
}
</script>

<style scoped>
.inline-block {
    margin-left: 10px;
    display: inline-block;
}
</style>
